<template>
  <div class="app-container">
    <!-- 备件分类 -->
    <!-- 查询和其他操作 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="分类名称">
        <el-input
          v-model="listQuery.fclassstname"
          clearable
          class="filter-item"
          style="width: 200px"
          placeholder="请输入分类名称"
        />
      </el-form-item>
      <el-form-item label="上级分类">
        <el-select v-model="listQuery.fparentno" filterable clearable class="filter-item" placeholder="请选择上级分类">
          <el-option
            v-for="item in getListfparentno"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <!-- v-permission="['part:partClass:read']" -->
        <el-button
          :style="{background:buttonColor.lookup,color:buttonColor.color}"
          round
          size="medium"
          class="filter-item"
          @click="handleFilter"
        >查找</el-button
        >
        <!-- v-permission="['part:partClass:create']" -->
        <el-button
          :style="{background:buttonColor.add,color:buttonColor.color}"
          round
          size="medium"
          class="filter-item"
          @click="handleCreate"
        >添加</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      :header-cell-style="tableColor"
      stripe
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
      <el-table-column :width="buttonColor.operationTwo" align="center" label="操作" class-name="small-padding">
        <template slot-scope="scope">
          <div class="operationButton">
            <div :style="{color:buttonColor.edit,cursor:'pointer'}" @click="handleUpdate(scope.row)">
              <img src="../../../public/images/edit.png" >
              编辑
            </div>
            <div :style="{color:buttonColor.delete,cursor:'pointer'}" @click="handleDelete(scope.row)">
              <img src="../../../public/images/del.png" >
              删除
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :index="indexMethod"
        align="center"
        label="序"
        type="index"
      />
      <el-table-column align="center" label="分类编号" prop="fclassstno" />
      <el-table-column align="center" label="分类名称" prop="fclassstname" />
      <el-table-column :formatter="formatfparentno" align="center" label="上级分类" prop="fparentno" />
      <el-table-column align="center" label="折扣年限" prop="fdiscmonth" />
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      width="auto"
    >
      <template slot="title">
        <div :style="titleColor">{{ textMap[dialogStatus] }}</div>
      </template>
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="auto"
        style="width: 400px; margin: 0 30px"
      >
        <el-form-item v-if="dialogStatus==='create'" label="分类编号" prop="fclassstno">
          <el-input v-model="dataForm.fclassstno" />
        </el-form-item>
        <el-form-item v-else label="分类编号" prop="fclassstno">
          <el-input :disabled="true" v-model="dataForm.fclassstno" />
        </el-form-item>
        <el-form-item label="分类名称" prop="fclassstname">
          <el-input v-model="dataForm.fclassstname" />
        </el-form-item>
        <el-form-item label="上级分类" prop="fparentno">
          <el-select v-model="dataForm.fparentno" style="width:100%" filterable clearable class="filter-item" placeholder="请选择上级分类">
            <el-option
              v-for="item in getListfparentno"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="折扣年限" prop="fdiscmonth">
          <el-input v-model.number="dataForm.fdiscmonth" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="dialogFormVisible = false">取消</el-button>
        <el-button
          v-if="dialogStatus == 'create'"
          :style="{background:buttonColor.confirm,color:buttonColor.color}"
          @click="createData"
        >确定</el-button
        >
        <el-button v-else :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.button-margin {
  margin: 2px 0px;
}
.el-button + .el-button {
  margin-left: 1px;
}
</style>

<script>
import {
  listpartClass,
  createpartClass,
  updatepartClass,
  deletepartClass
} from '@/api/partClass'
import Pagination from '@/components/Pagination'
import moment from 'moment'
import { tableColor, titleColor, buttonColor } from '@/filters/index'
import { getListArea } from '@/api/area'

export default {
  name: 'STsPartClass',
  components: { Pagination },
  data() {
    return {
      buttonColor: buttonColor,
      getListfparentno: [],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        fclassstname: undefined,
        fparentno: undefined,
        fclassstyle: undefined,
        flevel: undefined,
        fdiscmonth: undefined,
        fupddate: undefined,
        foperator: undefined,
        sort: 'create_time',
        order: 'desc'
      },
      dataForm: {
        fclassstno: undefined,
        fclassstname: undefined,
        fparentno: undefined,
        fclassstyle: undefined,
        flevel: undefined,
        fdiscmonth: undefined,
        fupddate: undefined,
        foperator: undefined,
        id: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      tableColor: tableColor,
      titleColor: titleColor,
      rules: {
        fclassstno: [{ required: true, message: '分类编号不能为空' }],
        fclassstname: [],
        fparentno: [],
        fdiscmonth: [
          {
            type: 'number',
            message: '折扣年限必须为数字值',
            transform: (value) => Number(value)
          }
        ],
        fupddate: [],
        foperator: []
      }
    }
  },
  created() {
    this.getList()
    getListArea({ flag: 21 })
      .then(response => {
        this.getListfparentno = response.data.data.list
      })
      .catch(() => {
        this.getListfparentno = []
      })
  },
  methods: {
    datetimeFormat(row, column) {
      const date = row[column.property]
      if (date === undefined || date === null) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    // 上级分类
    formatfparentno: function(row, column) {
      if (this.getListfparentno.length > 0) {
        for (let i = 0; i < this.getListfparentno.length; i++) {
          if (row.fparentno === this.getListfparentno[i].value) {
            return this.getListfparentno[i].label
          }
        }
        return ''
      } else {
        return ''
      }
    },
    getList() {
      this.listLoading = true
      listpartClass(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        fclassstno: undefined,
        fclassstname: undefined,
        fparentno: undefined,
        fclassstyle: undefined,
        flevel: undefined,
        fdiscmonth: undefined,
        fupddate: undefined,
        foperator: undefined,
        id: undefined
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      if (this.getListfparentno.length > 0) {
        this.dataForm.fparentno = this.getListfparentno[0].value
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dataForm.foperator = this.$store.state.user.id
          this.dataForm.fupddate = new Date()
          createpartClass(this.dataForm)
            .then((response) => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加备件分类成功'
              })
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dataForm.foperator = this.$store.state.user.id
          this.dataForm.fupddate = new Date()
          updatepartClass(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.fclassstno === this.dataForm.fclassstno) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新备件分类成功'
              })
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('是否要删除备件分类', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletepartClass(row)
          .then((response) => {
            this.$notify.success({
              title: '成功',
              message: '删除备件分类成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch((response) => {
            this.$notify.error({
              title: '失败',
              message: response
            })
          })
      })
    },
    indexMethod(index) {
      index = index + 1
      return index
    }
  }
}
</script>
